using UnityEngine;
using System.Collections;

public class BulletBehaviour : MonoBehaviour {

	public float damage = 1f;
	public bool penetrates = false;
	public float bulletsPerSecond = 5f;
	public float bulletSpeed = 25f;

	public bool ignoreWallImpacts = false;

	public float homingTurnSpeed = 0;
	public float homingRange = 5f;
	float homingDelay = 0.1f;

	public float splashRadius = 0;
	public float splashDamage = 0;
	public bool splashIsBurn = false;

	public AudioClip bulletFireSound;
	public AudioClip bulletHitSound;

	public GameObject debris;

	void Start() {
		//rigidbody2D.velocity = this.transform.rotation * new Vector3(0, bulletSpeed, 0);
	}

	void OnCollisionEnter2D( Collision2D colision ) {
		OnTriggerEnter2D(colision.collider);
	}

	void Update() {
		homingDelay -= Time.deltaTime;
		if(homingTurnSpeed > 0 && homingDelay <= 0) {
			Collider2D[] cols = Physics2D.OverlapCircleAll(this.transform.position, homingRange, 1 << (gameObject.layer==9 ? 10 : 8));

			Vector2 dir = rigidbody2D.velocity;
			float dist = Mathf.Infinity;

			foreach (Collider2D col in cols) {
				if(Vector2.Distance(col.transform.position, this.transform.position) < dist) {
					dir = col.transform.position - this.transform.position;
					dist = dir.magnitude;
				}
			}

			float desiredAngle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg - 90f;

			transform.rotation = Quaternion.RotateTowards( transform.rotation, Quaternion.Euler(0, 0, desiredAngle), homingTurnSpeed * Time.deltaTime );

			rigidbody2D.velocity = transform.rotation * new Vector2(0, bulletSpeed) ;


		}
	}

	void OnTriggerEnter2D( Collider2D col ) {

		Health h = col.GetComponent<Health>();
		if(h != null) {


			float d = Mathf.Min(h.hps, damage);

			if(gameObject.layer == 9) {
				h.TakeDamage(d * GameManager.Instance.bulletBonusDamagePerc);
				h.TakeDamage(GameManager.Instance.bulletBonusFireDamage, true);

				if(GameManager.Instance.chillBullets && Random.Range(0f, 1f) <= 0.5f ) {
					MonsterBehaviour mb = h.GetComponent<MonsterBehaviour>();
					if(mb != null) {
						mb.chillTime = 2f;
					}
				}
			}
			else {
				// Monster doing damage to player stuff
				h.TakeDamage(d * GameManager.Instance.DifficultyExponential());
			}

			if(penetrates)
				damage -= d;
			else
				damage = 0;
		}
		else {
			//  Hit a wall or something.
			if(!ignoreWallImpacts)
				damage = 0;
		}

		if(damage <= 0) {
			if(splashDamage > 0) {
				GameObject.FindObjectOfType<GameManager>().DoSplashDamage(transform.position, splashRadius, splashDamage * GameManager.Instance.bulletBonusDamagePerc, splashIsBurn,  1 << (gameObject.layer==9 ? 10 : 8));
			}

			if(bulletHitSound != null)
				AudioSource.PlayClipAtPoint(bulletHitSound, Vector3.zero, 0.3f);

			if(debris != null) {
				Instantiate(debris, transform.position, Quaternion.identity);
			}

			Destroy (gameObject);
		}
	}



}
